package com.shuhg.book.util
{
	import com.adobe.serialization.json.JSON;
	import com.hurlant.crypto.Crypto;
	import com.hurlant.crypto.prng.Random;
	import com.hurlant.crypto.symmetric.DESKey;
	import com.hurlant.crypto.symmetric.ICipher;
	import com.shuhg.bean.BookShow;
	import com.shuhg.bean.Potil;
	import com.shuhg.book.write.BookModel;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.IBitmapDrawable;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;
	
	import mx.containers.Canvas;
	import mx.controls.Button;
	import mx.controls.HTML;
	import mx.controls.Image;
	import mx.graphics.codec.JPEGEncoder;
	import mx.managers.PopUpManager;
	
	import qs.controls.FlexBook;
	
	import shg.book.size.BookData;
	import shg.book.util.MD5;
	import shg.book.view.MoveBook;
	
	import spark.components.RichEditableText;
	import spark.primitives.Graphic;

	public class BookTool
	{
		static public  var flexBook:shuhg;
		
		
		public function BookTool()
		{
		}
		public static function makeMap(bookPotil:Object,currentPage:Number,potilMap:Object,key:String,value:String):void{
			potilMap[key]=value;
			//批注同步操作
			synchroPotil(bookPotil,potilMap,currentPage);
		}
		/**
		 * 根据ID修改指定的批注的备注
		 * */
		public static function updatePotil(bookPotil:Object,currentPage:Number,potilMap:Object,key:String,content:String):void{
			var str:String = potilMap[key];
			var decoded:Object=JSON.decode(str);
			var potil:Potil = makeObject(new Potil(),decoded) as Potil;
			potil.content=content;
			potilMap[key]=JSON.encode(potil);
			//批注同步操作
			synchroPotil(bookPotil,potilMap,currentPage);
			
		}
		/**
		 * 拖拉结束后更新坐标
		 * */
		public static function updatePosition(bookPotil:Object,currentPage:Number,potilMap:Object,key:String,x:Number,y:Number):void{
			var str:String = potilMap[key];
			var decoded:Object=JSON.decode(str);
			var potil:Potil = makeObject(new Potil(),decoded) as Potil;
			potil.startX=x;
			potil.startY=y;
			potilMap[key]=JSON.encode(potil);
			//批注同步操作
			synchroPotil(bookPotil,potilMap,currentPage);
		}
		
		/**
		 * 这个方法将json转为对象
		 * */
		public static function makeObject(_object:Object,_decoded:Object):Object{
			for(var key:String in _decoded){
				_object[key]=_decoded[key];
			}
			return _object;
		}
		/**
		 * 获取备注的文本
		 * */
		public static function getContent(_potil:Object,key:String):String{
			if(_potil[key]==null)
				return "";
			//获取到指定的批准
			var _decoded:Object = JSON.decode(_potil[key]);
			//将批准转为对象
			var potil:Potil = makeObject(new Potil(),_decoded) as Potil;
			return potil.content;
		}
		/**
		 * 将最新批注同步总批准关联数组
		 * */
		public static function synchroPotil(_allPotil:Object,_pagePotil:Object,_pageIndex:Number):void{
			//将页面批准通过JSON转为字符串
			var pagePotil:String = JSON.encode(_pagePotil);
			//将页面批注同步到总批准
			_allPotil[_pageIndex]=pagePotil;
		}
		/**
		 * 更新批注到文件,现在只是保存到临时文件
		 *
		private static function updateFile(bookPotil:Object):void{
			try{
				trace(JSON.encode(bookPotil));
				trace("文件保存成功");
			}catch(error:Error){
				trace("文件保存失败"+error.toString());
			}
		} */
		
		/**
		 * 文本内容加密
		 * */
		static public function encrypt(keyByte:ByteArray,contentByte:ByteArray):ByteArray{
			try{
				//第一次加密：使用128位AES算法加密
				var aes:ICipher = Crypto.getCipher("aes-ecb", keyByte, Crypto.getPad("pkcs5"));
				aes.encrypt(contentByte); 
				//第二次加密(将密钥采用MD5加密)
				var md5:MD5 = new MD5();
				keyByte = md5.getByteMd5(keyByte);
				//第三次加密 des加密（将第一次加密得到的密文再次加密）
				var des:DESKey = new DESKey(keyByte);
				des.decrypt(contentByte,0);
			}catch(error:Error){
				trace("加密发生异常:"+error.toString());
			}
			return contentByte;
		}
		/**
		 * 文本解密
		 * */
		static  public function decrypt(keyByte:ByteArray,contentByte:ByteArray):ByteArray{
			try{
				//第一次解密：MD5(获取密钥)
				var md5:MD5 = new MD5();
				var md5Key:ByteArray= md5.getByteMd5(keyByte);
				//第二次解密:DESC
				var des:DESKey = new DESKey(md5Key);
				des.encrypt(contentByte,0);
				//第三次解密：使用128位AES算法加密
				var aes:ICipher = Crypto.getCipher("aes-ecb", keyByte, Crypto.getPad("pkcs5"));
				aes.decrypt(contentByte); 
			}catch(error:Error){
				trace("解密发生异常"+error.toString());
			}
			return contentByte;
		}
		/**
		 * 写出数据
		 * */
		static public function writeFile(byte:ByteArray):void{
			byte.position=0;
			var file:File=null;
			var index:int=0;
			var lastName:String="";
			do{
				if(index>0)
					lastName="["+index.toString()+"]";
				file=File.desktopDirectory.resolvePath(BookData.bookName+lastName+BookData.EXTENSION);
				index++;
				trace(file.nativePath);
			}while(file.exists);
			var fileStream:FileStream=new FileStream();
			fileStream.open(file,FileMode.WRITE);
			fileStream.writeBytes(byte);
			fileStream.close();
			//打开文件所在位置
			var readBook:ReadBook=new ReadBook();
			readBook.filePath = file.nativePath;
			readBook.selectFile(null);
		}
		
		/**
		 * 传进来一个整数返回一个有0组成的字符串才长度为15
		 * */
		static public function setLength(_str:Number):String{
			var str_length:String=String(_str);
			var str:String="";
			if(str_length!=null){
				for(var r:int=0;r<BookData.EDITION_LENGTH-String(_str).length;r++){
					str+="0";
				}
			}else{
				return "000000000000000";
			}
			str_length=str+str_length;
			return str_length;
		}
		/**
		 * 存储在文件
		 * bookParameter书籍的参数信息
		 * bookByteArray书籍的内容信息（包括书籍的版本信息、目录、正文、封面等等）
		 * */
		static public function makeNewByte(bookParameter:String, bookByteArray:ByteArray):ByteArray{
			try{
				//书籍的参数信息
				var parameter:ByteArray = new ByteArray();
				parameter.writeUTFBytes(bookParameter);
				//新的字节数组
				var byte:ByteArray = new ByteArray();
				//一、存储书籍参数信息长度
				byte.writeUTFBytes(setLength(parameter.length));
				//二、书籍存储参数信息
				byte.writeBytes(parameter);
				//三、存储书籍信息
				byte.writeBytes(bookByteArray);
				return byte;
			}catch(error:Error){
				trace(error.message);
			}
			return null;
		}
		/**
		 * 创建页面
		 * */
		static public function getTextFied():TextField{
			//TextField基本参数设置
			var textField:TextField=new TextField();
			textField.wordWrap=true;		//允许自动换行
			textField.multiline=true;
			textField.width=BookData.getContentWidth();	//每行文本的显示宽度
			textField.height=BookData.getContentHeigth();
			//给文本添加样式
			var format:TextFormat = new TextFormat();
			format.font = BookData.FONT;
			format.color = BookData.COLOR;
			format.size = BookData.SIZE;
			format.leading=BookData.LEADING;
			format.letterSpacing=BookData.LETTERSPACING;
			//设置文本样式
			textField.defaultTextFormat=format;
			return textField;
		}
		
		static public function getTextFiledHTML(content:String):TextField{
			var html:HTML=new HTML();
			var textFiled:TextField=getTextFied();
			html.addChild(textFiled);
			textFiled.appendText(content);
			return textFiled;
		}
		
		static public function initApp(_bookModel:BookModel):void{
			try{
				if(_bookModel.book.content.length>2)
				{
					var _length:Number=_bookModel.book.content.length-2;
					_bookModel.book.content.splice(1,_length);
				}
			}catch(error:Error){
				trace(error.toString());
			}
		}
		/**
		 * 绘制书籍的边框30  =18*x  30/18
		 * */
		public static function drawBorder(_source:Image,_width:Number,_heigth:Number):Bitmap{
			var bit:BitmapData = new BitmapData(_width,_heigth);
			var matrix:Matrix = new Matrix();
			matrix.scale(_width/_source.width,_heigth/_source.height);
			bit.draw(_source,matrix);
			var data:Bitmap=new Bitmap(bit);
			return data;
		}
		/**
		 * 作者背景
		 * */
		public static function authorDraw(coverBg:Class,book:FlexBook):Graphic{
			var m:Matrix = new Matrix();
			var s:Graphic =new Graphic();
			var cover:BitmapData=new coverBg().bitmapData;
			m.scale(book.width/cover.width,cover.height/book.height);
			s.graphics.beginBitmapFill(cover,m);
			s.graphics.drawRect(0,0,book.width,book.height);
			s.graphics.endFill();
			return s;
		}
		
		/**
		 * 获取作者编辑器
		 * */
		public static function authorEdit(_width:Number,_height:Number,_x:Number,_y:Number):RichEditableText{
			var author:RichEditableText=new RichEditableText();
			author.width=_width;
			author.height=_height;
			author.x=_x;
			author.y=_y;
			return author;
		}
		/**
		 * 获取拖拉后的书籍存储在哪个位置
		 * */
		public static function getBookIndex(id:String):Number{
			switch(id){
				case "c11":
					return 1;
					break;
				case "c12":
					return 2;
					break;
				case "c13":
					return 3;
					break;
				case "c14":
					return 4;
					break;
				case "c15":
					return 5;
					break;
				case "c16":
					return 6;
					break;
				//二层
				case "c21":
					return 7;
					break;
				case "c22":
					return 8;
					break;
				case "c23":
					return 9;
					break;
				case "c24":
					return 10;
					break;
				case "c25":
					return 11;
					break;
				case "c26":
					return 12;
					break;
				//三层
				case "c31":
					return 13;
					break;
				case "c32":
					return 14;
					break;
				case "c33":
					return 15;
					break;
				case "c34":
					return 16;
					break;
				case "c35":
					return 17;
					break;
				case "c36":
					return 18;
					break;
				//四层
				case "c41":
					return 19;
					break;
				case "c42":
					return 20;
					break;
				case "c43":
					return 21;
					break;
				case "c44":
					return 22;
					break;
				case "c45":
					return 23;
					break;
				case "c46":
					return 24;
					break;
			}
			return 0;
		}
		/**
		 * 点击展开按钮调用的方法
		 * */
		
		static public function btnClick(evt:MouseEvent):void{
			var btn:Button = Button(evt.currentTarget);
			var canvas:Canvas = Canvas(btn.parent);//获取button按钮的父类容器
			var moveBook:MoveBook = new MoveBook;
			for(var i:Number=0;i<canvas.numChildren-1;i++){
				var image:BookShow = BookShow(canvas.getChildAt(i));//从最下层依次获取书籍封面
				var data:BitmapData = Bitmap(image.content).bitmapData;
				var bitmap:Bitmap = new Bitmap(data);
				var tempImage:BookShow = new BookShow;//copy一份书籍封面
				tempImage.source = bitmap;
				tempImage.bookBean=image.bookBean;
				tempImage.height = image.height;
				tempImage.width = image.width;
				tempImage.maintainAspectRatio = false;
				moveBook.booksArr.push(tempImage);//将copy的书籍封面依次加入弹出窗口的数组中
			}
			PopUpManager.addPopUp(moveBook, flexBook, true);   
			PopUpManager.centerPopUp(moveBook); 
		}
		
	}
}